package TCP;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TCPServer {
    private int serverPort;


    private ServerSocket service = null;

    public TCPServer(int serverPort) throws IOException {
        this.service = new ServerSocket(serverPort);
    }

    public void start() throws IOException {
        System.out.println("服务器启动！");
        Socket socket = service.accept();
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();
            PrintWriter writer = new PrintWriter(outputStream);
            Scanner scannerConsle = new Scanner(inputStream)){

            while (true){
                String request = scannerConsle.next();
                String response = process(request);
                writer.println(response);
                writer.flush();

                System.out.printf("[%s:%d, req: %s, resp: %s]", socket.getInetAddress().toString(),
                        socket.getPort(), request, response);
            }

        }
    }

    public String process(String request){
        return request;
    }

    public static void main(String[] args) throws IOException {
        TCPServer server = new TCPServer(9091);
        server.start();
    }
}
